package com.tanhua.server.controller;


import com.tanhua.model.domian.UserInfo;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.server.UserInfoService;
import com.tanhua.server.server.UserServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/user")
/**
 * 登录相关
 */
public class UserController {


    @Autowired
    private UserServer userServer;
    @Autowired
    private UserInfoService userInfoService;


    /**
     * 发送验证码
     * @param map
     * @return
     */
    @PostMapping("login")
    public ResponseEntity login(@RequestBody Map<String, String> map) {
        //获取手机号
        String phone = map.get("phone");
        //获取验证码
        userServer.sendCode(phone);
        //返回数据
        return ResponseEntity.ok(null);
    }

    /**
     * 验证码校验,登录
     * @param map
     * @return
     */
    @PostMapping("loginVerification")
    public ResponseEntity loginVerification(@RequestBody Map<String, String>map) {
        //获取手机号验证码
        String phone = map.get("phone");
        String code = map.get("verificationCode");
        //登录
        Map retMap = userServer.loginVerification(phone,code);
        //返回数据
        return ResponseEntity.ok(retMap);

    }

    /**
     * 完善用户资料 userinfo表
     * @param userInfo
     *
     * @return
     */
    @PostMapping("loginReginfo")
    public ResponseEntity loginReginfo(@RequestBody UserInfo userInfo){
        //在token中获取本主账号ID，设置给userinfo表

        userInfo.setId(UserHolder.getUserId());
        //调用service保存进数据库
        userInfoService.save(userInfo);
        return ResponseEntity.ok(null);

    }

    /**
     * 上传用户头像
     * @param headPhoto
     *
     * @return
     * @throws IOException
     */
    @PostMapping("loginReginfo/head")
    public ResponseEntity headd(MultipartFile headPhoto) throws IOException {

        //调用service完成头像更新
        userInfoService.updatehead(headPhoto,UserHolder.getUserId());
        return ResponseEntity.ok(null);
    }
}
